<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <!-- 警告区域 -->
      <el-alert
        title="注意:只允许为第三等级分类设置相关参数"
        type="warning"
        :show-icon="true"
        :closable="false"
      >
      </el-alert>
      <!-- 选择商品分类区域 -->
      <el-row class="cat-opt">
        <el-col>
          <span>选择商品分类：</span>
          <!-- 选择商品分类级联选择器 -->
          <el-cascader
            v-model="selectValue"
            :options="cateList"
            :props="{
              expandTrigger: 'hover',
              value: 'cat_id',
              label: 'cat_name',
              children: 'children',
            }"
            @change="handleChange"
            style="width: 400px"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- Tabs区域 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="用户管理" name="many">
          <el-button
            type="primary"
            size="mini"
            style="margin-right: 10px"
            :disabled="isDisabled"
            @click="addeDialogVisible = true"
            >添加参数</el-button
          >
          <!-- 动态参数表格 -->
          <el-table :data="manyTableData" style="width: 100%">
            <!-- 展开行 -->
            <el-table-column type="expand" label="">
              <template slot-scope="scope">
                <!-- 循环渲染tag标签 -->
                <el-tag
                  type="success"
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="handleClose(index, scope.row)"
                  >{{ item }}</el-tag
                >
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  type="success"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                  style="width: 170px"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称" width="180">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <!-- 修改按钮 -->
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  style="margin-right: 10px"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <!-- 删除按钮 -->
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="配置管理" name="only">
          <el-button
            type="primary"
            size="mini"
            style="margin-right: 10px"
            :disabled="isDisabled"
            @click="addeDialogVisible = true"
            >添加参数</el-button
          >
          <!-- 静态参数表格 -->
          <el-table :data="onlyTableData" style="width: 100%">
            <!-- 展开行 -->
            <el-table-column type="expand" label="">
              <template slot-scope="scope">
                <!-- 循环渲染tag标签 -->
                <el-tag
                  type="success"
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="handleClose(index, scope.row)"
                  >{{ item }}</el-tag
                >
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  type="success"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                  style="width: 170px"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称" width="180">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <!-- 修改按钮 -->
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  style="margin-right: 10px"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <!-- 删除按钮 -->
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!--添加参数的弹窗 -->
    <el-dialog
      :title="activeName === 'many' ? '添加动态参数' : '添加静态属性'"
      :visible.sync="addeDialogVisible"
      @close="addDialogclosed"
    >
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item
          :label="activeName === 'many' ? '动态参数' : '静态属性'"
          prop="attr_name"
        >
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addeDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改参数的弹窗 -->
    <!--添加参数的弹窗 -->
    <el-dialog
      :title="activeName === 'many' ? '修改动态参数' : '修改静态属性'"
      :visible.sync="aeditDialogVisible"
      @close="editDialogclosed"
    >
      <el-form
        :model="editForm"
        :rules="addFormRules"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item
          :label="activeName === 'many' ? '动态参数' : '静态属性'"
          prop="attr_name"
        >
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editeDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script type="text/ecmascript-6">
import {
  reqCateList,
  reqCateById,
  reqAddParams,
  reqQueryParamsById,
  reqEditParamsById,
  reqDeleteParams,
} from "../../api";
export default {
  data() {
    return {
      // 商品分类列表
      cateList: [],
      // 联级选择器选中的值（值为id的数组）
      selectValue: [],
      // 选中的tabs-item的name值
      activeName: "many",
      // 动态属性数据(用户可以管理的属性)
      manyTableData: [],
      // 静态属性数据（用户不能操控的属性）
      onlyTableData: [],
      // 控制添加参数数据的对话框
      addeDialogVisible: false,
      // 添加参数表单
      addForm: {
        attr_name: "",
      },
      addFormRules: {
        attr_name: [
          { required: true, message: "请输入参数属性", trigger: "blur" },
        ],
      },
      // 当前的attrId 当前的属性 ID  从scope.row中获取的
      attrId: 0,
      // 显示隐藏修改参数弹窗
      aeditDialogVisible: false,
      editForm: { attr_name: "" },
    };
  },
  mounted() {
    this.getCateList();
  },
  methods: {
    // 获取商品分类列表
    async getCateList() {
      const result = await reqCateList();
      if (result.meta.status != 200)
        return this.$message.error(result.meta.msg);
      this.cateList = result.data;
    },
    // 联级选择器,选中后，会触发这个函数
    handleChange(value) {
      //  设置只能选中三级分类，不能选中二级一级分类 将selectValue设置为[]
      if (value.length != 3) {
        this.selectValue = [];
        // 动态属性数据清空
        this.manyTableData = [];
        // 静态属性数据清空
        this.onlyTableData = [];
      }
      // 获取参数列表数据;
      this.getParamsDate();
    },
    // 切换tabs后产生触发的函数
    handleClick() {
      this.getParamsDate();
    },
    // 获取参数列表数据
    async getParamsDate() {
      // 发请求获取参数列表数据
      let id;
      if (this.selectValue.length === 3) {
        id = this.selectValue[2];
      } else {
        id = 0;
      }
      const sel = this.activeName;
      const result = await reqCateById({ id, sel });
      result.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(",") : [];
        // 控制文本框的显示与隐藏
        item.inputVisible = false;
        item.inputValue = "";
      });
      if (result.meta.status != 200)
        return this.$message.error(result.meta.msg);
      if (this.activeName === "many") {
        this.manyTableData = result.data;
      } else {
        this.onlyTableData = result.data;
      }
    },
    addManyData() {
      this.addeDialogVisible = true;
    },
    addDialogclosed() {
      this.$refs.addFormRef.resetFields();
    },
    // 点击确认按钮，添加参数
    addParams() {
      // 进行预验证
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return;
        const cateId = this.selectValue[2];

        const result = await reqAddParams({
          cateId,
          attr_sel: this.activeName,
          attr_name: this.addForm.attr_name,
        });
        if (result.meta.status != 201)
          return this.$message.error(result.meta.msg);
        this.getParamsDate();
        this.addeDialogVisible = false;
      });
    },
    // 点击按钮， 显示编辑弹窗
    async showEditDialog(attrId = attrId) {
      this.attrId = attrId;
      const cateId = this.selectValue[2];
      // 根据 ID 查询参数
      const result = await reqQueryParamsById({
        cateId,
        attrId,
        attr_sel: this.activeName,
      });
      if (result.meta.status != 200)
        return this.$message.error(result.meta.msg);
      this.editForm = result.data;
      this.aeditDialogVisible = true;
    },
    editDialogclosed() {
      this.$refs.editFormRef.resetFields();
    },
    // 点击确认编辑按钮
    editParams() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return;

        const cateId = this.selectValue[2];
        // 发请求编辑提交参数
        const result = await reqEditParamsById({
          cateId,
          attrId: this.attrId,
          attr_name: this.editForm.attr_name,
          attr_sel: this.activeName,
        });
        if (result.meta.status != 200)
          return this.$message.error(result.meta.msg);
        this.$message.success(result.meta.msg);
        this.getParamsDate();
        this.aeditDialogVisible = false;
      });
    },
    // 根据id值删除对应的商品参数
    removeParams(attrId) {
      this.$confirm("此操作将永久删除该商品参数, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          // 发请求删除对应的商品参数
          const cateId = this.selectValue[2];
          const result = await reqDeleteParams({
            cateId,
            attrId,
          });
          if (result.meta.status != 200)
            return this.$message.error(result.meta.msg);
          this.$message.success(result.meta.msg);
          this.getParamsDate();
        })
        .catch(() => {});
    },
    //文本框失去焦点或者按下enter键都会触发这个事件
    handleInputConfirm(row) {
      // 如果文本框输入为0
      if (row.inputValue.trim() === "") {
        row.inputValue = "";
        row.inputVisible = false;
        return;
      }
      // 如果值不为空
      row.attr_vals.push(row.inputValue.trim());
      row.inputValue = "";
      row.inputVisible = false;
      // 需要发请求，在后台数据库中进行保存
      this.saveAttrValues(row);
    },
    async saveAttrValues(row) {
      // 需要发请求，在后台数据库中进行保存
      const cateId = this.selectValue[2];
      const result = await reqEditParamsById({
        cateId,
        attrId: row.attr_id,
        attr_sel: row.attr_sel,
        attr_name: row.attr_name,
        attr_vals: row.attr_vals.join(","),
      });
      if (result.meta.status != 200)
        return this.$message.error(result.meta.msg);
      this.$message.success(result.meta.msg);
      this.getParamsDate();
    },
    // 点击按钮，显示文本框
    showInput(row) {
      row.inputVisible = true;

      // 当页面dom加载完后调用，自动获得焦点
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    // 删除对应的参数可选项
    handleClose(i, row) {
      row.attr_vals.splice(i, 1);
      // 需要发请求，在后台数据库中进行保存
      this.saveAttrValues(row);
    },
  },
  computed: {
    // 判断是否禁用tabs里得按钮
    isDisabled() {
      return this.selectValue.length === 3 ? false : true;
    },
  },
};
</script>
<style lang="less" scoped>
.cat-opt {
  margin: 20px 0;
}
.el-tag {
  margin: 0 15px;
}
</style>